﻿using System;
using System.Linq;
using System.Web.Mvc;
using MvcContrib.Sorting;
using MvcContrib.UI.Grid;
using QDT.Common;
using QDT.Core.Domain;
using QDT.Core.Members;
using QDT.Core.Orders;
using QDT.Common.Data;
using QDT.Core.Payments;
using QDT.MVC.Security;
using QDT.Payment;
using QDT.Services.Orders;

namespace QDT.Web.Admin.Controllers
{
    [SecurityModule(Name = "订单管理")]
    public class OrderController : BaseController {
        
        private readonly IOrderService _orderService;

        public OrderController(IOrderService orderService) {

            _orderService = orderService;

        }

        [SecurityNode(Name = "充值列表")]
        public ActionResult Index(int? page, GridSortOptions sort, string orderNo, string username, DateTime? start, DateTime? end, decimal max = 0, decimal min = 0)
        {
            User user = null;

            if (!string.IsNullOrWhiteSpace(username))
            {
                user = DbProvider.D<User>().FirstOrDefault(x => x.UserName == username);
            }

            var filter = PredicateExtensionses.True<ChargeOrder>();

            if (!string.IsNullOrWhiteSpace(orderNo)) filter = filter.And(x => x.OrderSN == orderNo);

            if (user != null) filter = filter.And(x => x.UserID == user.ID);

            if (start.HasValue) filter = filter.And(x => x.CreateTime >= start.Value);

            if (end.HasValue) filter = filter.And(x => x.CreateTime <= end.Value);

            if (min > 0) filter = filter.And(x => x.TotalPrice >= min);

            if (max > 0 && max > min) filter = filter.And(x => x.TotalPrice <= max);

            const int pageSize = 20;

            var pageNumber = page ?? 1;

            if (sort.Column == null) sort.Column = "ID";

            ViewData["sort"] = sort;

            var deals = DbProvider.D<ChargeOrder>().Where(filter.And(x => !x.IsDelete)).OrderBy(sort.Column, sort.Direction == SortDirection.Descending);

            return View(deals.ToPagedList(pageNumber - 1, pageSize));
        }

        //[SecurityNode(Name = "管理员收款")]
        public ActionResult AdminProcess(int id)
        {
            
            var order=DbProvider.GetByID<ChargeOrder>(id);
            
            if (order == null) return Error("订单不存在.");

            var admin = DbProvider.D<AdminUser>().FirstOrDefault(x => x.Name == User.Identity.Name);

            _orderService.AdminPay(admin,order);

            return Success("收款处理成功！");
        }

        [SecurityNode(Name = "删除充值订单")]
        public ActionResult Delete(int[] id)
        {
            IoC.Resolve<IOrderService>().DeleteOrder(id);
            return Success("删除成功");
        }

        [HttpPost]
        [SecurityNode(Name = "恢复充值订单")]
        public ActionResult Restore(int[] id)
        {
            IoC.Resolve<IOrderService>().RestoreOrder(id);
            return Success("恢复成功");
        }

        [SecurityNode(Name = "回收站")]
        public ActionResult Trash(int? page, GridSortOptions sort, string username, int? orderId)
        {

            User user = null;

            if (!string.IsNullOrWhiteSpace(username))
            {
                user = DbProvider.D<User>().FirstOrDefault(x => x.UserName == username);
            }

            var filter = PredicateExtensionses.True<ChargeOrder>();

            if (orderId != null && orderId != 0) filter = filter.And(x => x.ID == orderId);

            if (user != null) filter = filter.And(x => x.UserID == user.ID);

            const int pageSize = 20;

            var pageNumber = page ?? 1;

            if (sort.Column == null) sort.Column = "ID";

            ViewData["sort"] = sort;

            var deals = DbProvider.D<ChargeOrder>().Where(filter.And(x => x.IsDelete)).OrderBy(sort.Column, sort.Direction == SortDirection.Descending);

            return View(deals.ToPagedList(pageNumber - 1, pageSize));
        }

        //[SecurityNode(Name = "订单日志")]
        public ActionResult OrderLog(int id)
        {
            return PartialView(DbProvider.GetByID<ChargeOrder>(id));
        }

        [SecurityNode(Name = "收款单列表")]
        public ActionResult Notice(int? page, GridSortOptions sort, string orderSn, string noticeSn, string username, DateTime? createTime)
        {
            var filter = PredicateExtensionses.True<PaymentNotice>();

            if (createTime!=null)
            {
                var startTime = ((DateTime) createTime).Date;
                var endTime = startTime.AddDays(1);
                filter = filter.And(x => x.CreateTime >= startTime && x.CreateTime < endTime);
            }

            if (!string.IsNullOrWhiteSpace(orderSn))
            {
                var order = DbProvider.D<ChargeOrder>().FirstOrDefault(x => x.OrderSN == orderSn);
                if (order != null){
                    var orderId = order.ID;
                    filter = filter.And(x => x.OrderId == orderId);
                }
            }

            User user = null;

            if (!string.IsNullOrWhiteSpace(username))
            {
                user = DbProvider.D<User>().FirstOrDefault(x => x.UserName == username);
            }

            if (user != null) filter = filter.And(x => x.UserId == user.ID);

            if (!string.IsNullOrWhiteSpace(noticeSn)) filter = filter.And(x => x.NoticeSn == noticeSn);

            const int pageSize = 20;

            var pageNumber = page ?? 1;

            if (sort.Column == null) sort.Column = "ID";

            ViewData["sort"] = sort;

            var notices = DbProvider.D<PaymentNotice>().Where(filter).OrderBy(sort.Column, sort.Direction == SortDirection.Descending);

            if (createTime!=null)
            {
                ViewBag.TotalCharge = notices.Any() ? notices.Where(x => x.IsPaid).Sum(x => x.Money) : 0;
                ViewBag.ChargeCount = notices.Any() ? notices.Count(x => x.IsPaid) : 0;
                ViewBag.TotalChinaBank = notices.Any(x => x.IsPaid && x.PaymentKey.Equals("ChinaBankPayment")) ? notices.Where(x => x.IsPaid && x.PaymentKey.Equals("ChinaBankPayment")).Sum(x => x.Money) : 0;
                ViewBag.ChinaBankCount = notices.Any() ? notices.Count(x => x.IsPaid && x.PaymentKey.Equals("ChinaBankPayment")) : 0;
                ViewBag.TotalUnionPay = notices.Any(x => x.IsPaid && x.PaymentKey.Equals("UnionPayPayment")) ? notices.Where(x => x.IsPaid && x.PaymentKey.Equals("UnionPayPayment")).Sum(x => x.Money) : 0;
                ViewBag.UnionPayCount = notices.Any() ? notices.Count(x => x.IsPaid && x.PaymentKey.Equals("UnionPayPayment")) : 0;
            }

            return View(notices.ToPagedList(pageNumber - 1, pageSize));
        }

        //[SecurityNode(Name = "查询充值")]
        public ActionResult InchargeQuery(int orderid)
        {
            var order = DbProvider.GetByID<ChargeOrder>(orderid);
            if (order == null) return Error("无效ID");
            var notice = DbProvider.D<PaymentNotice>().FirstOrDefault(x => x.OrderId == orderid);
            if (notice == null) return Error("无效ID");

            var payOrder = new PaymentOrder()
            {
                CreateTime = notice.CreateTime,
                PaymentNo = notice.NoticeSn,
                Money = notice.Money
            };

            var result = IoC.Resolve<IPayment>().InchargeQueryRequest(payOrder);

            if (result)
            {
                _orderService.PayFinished(payOrder);
            }

            return Success(result.ToString());

        }


    }
}
